package com.thoughtworks.biblioteca.dao.file;

import com.thoughtworks.biblioteca.model.Book;
import com.thoughtworks.biblioteca.dao.BookDao;

import java.util.List;
import java.util.ArrayList;
import java.io.*;


public class BookFileDao implements BookDao {

    public boolean isExsitingBook(int bookID) {

        boolean isExsitMovie = false;

        List<Book> books = getAllBooks();

        for (Book book : books) {
            if (bookID == book.getId()) {
                isExsitMovie = true;
                break;
            }
        }

        return isExsitMovie;
    }

    public List<Book> getAllBooks() {
        List<Book> books = new ArrayList<Book>();
        try {
            File f = new File("resources/book.txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    new FileInputStream(f)));
            String bookSummary;
            while ((bookSummary = br.readLine()) != null) {
                Book tempBook = getBookFrom(bookSummary);
                books.add(tempBook);
            }
        } catch (IOException e) {
            //throw new MyIOException("My custom message",e);
        }
        return books;
    }

    Book getBookFrom(String bookSummary) {
        String[] attr = bookSummary.split("[|]");

        int id = Integer.parseInt(attr[0].trim());
        String name = attr[1].trim();
        String author = attr[2].trim();

        return new Book(id, name, author);
    }
}
